<template>
    <ContentBase>
        <span >聊天室当前人数:{{user_count}}</span>
        <div class="card">
            <div class="card-body">
                
                <div class="list-group" style="overflow-y: scroll; overflow-x: hidden; height: 60vh;" >
                    <div v-for="(message,index) in messages" :key="index">

                        <div v-if="store.state.user.id!=message.userId" style="margin-bottom: 20px;" class="row">
                            <div class="col-1 img-field">
                                <img class="mr-3 rounded-circle img-fluid" style="height: 8vh;" :src="message.userPhoto">
                            </div>
                            <div class="col-11">

                                    <p style="float: left;">{{message.content}}</p>

                            </div>
                        </div>

                        <div v-else style="margin-bottom: 20px;" class="row">
                            <div class="col-11" >

                                    <p style="float: right;">{{message.content}}</p>

                            </div>
                            <div class="col-1 img-field">
                                <img class="mr-3 rounded-circle img-fluid" style="height: 8vh;" :src="message.userPhoto">
                            </div>
                            
                        </div>
                    </div>
                    
                </div>

                  <div class="form-floating">
                    <textarea v-model="textword" class="form-control" placeholder="Leave a comment here" id="floatingTextarea"></textarea>
                    <label for="floatingTextarea">输入聊天信息</label>
                  </div>
                  <button type="button" style="float: right;" class="btn btn-outline-info" @click="sendmessage">发送</button>
            </div>
        </div>
    </ContentBase>
</template>

<script>
import ContentBase from '../components/ContentField';
import { ref } from 'vue'
import { useStore } from "vuex" //引入全局变量
import { onMounted, onUnmounted } from "vue";
export default {

    name: 'pkChat',
    components: {
        ContentBase,
    },
    setup() {

        const store = useStore();//拿出全局变量
        //字符串中有${}表达式操作的话要用``，不能用引号（这里是测试用，所以先不传token，传id）
        const socketUrl = `ws://127.0.0.1:3000/websocket/message/${store.state.user.token}/`;

        let messages = ref([]);
        let socket = null;
        let user_count = ref(0);

        onMounted(() => { //当当前页面打开时调用（实际是当前组件被挂载完成后调用）
            
            socket = new WebSocket(socketUrl); //js自带的WebSocket()
            socket.onopen = () => { //连接成功时调用的函数
                console.log("connected");
                socket.send(JSON.stringify({//表示把json数据转换成字符串
                    event:"init",
                }));
            }

            socket.onmessage = msg => { //前端接收到信息时调用的函数，msg是后端传来的数据
                const data = JSON.parse(msg.data); //拿到数据（不同的框架数据定义的格式不一样）

                if(data.event=="send"){
                    messages.value =  data.message;
                }else if(data.event=="init"){
                    messages.value =  data.message;
                    user_count.value = data.user_count;
                }
                
            }
            socket.onclose = () => { //链接断开时调用的函数
                console.log("disconnected")
            }
            
        });


        onUnmounted(() => { //当当前页面关闭时调用
            
            socket.close(); //卸载的时候断开连接，实际在这里调用了上面onclose后面的函数
            //注意一定要手动断开链接，否则会一直创建新连接
        });




        let textword = ref("");

        const sendmessage = ()=>{

            if(socket!=null)
            socket.send(JSON.stringify({//表示把json数据转换成字符串
                    event:"send",
                    content:textword.value,
                }));

                textword.value="";
            console.log("发送"+textword.value);
        }
        
        return{
            textword,
            sendmessage,
            messages,
            store,
            user_count
        }
    }
}

</script>


<style scoped>

.list-group {
  overflow-y: scroll; /* 显示滚动条 */
  height: 200px; /* 设置列表的高度 */
  scroll-behavior: smooth; /* 平滑滚动效果 */
}

.list-group::-webkit-scrollbar {
  width: 8px; /* 滚动条的宽度 */
}

.list-group::-webkit-scrollbar-thumb {
  background-color: #ccc; /* 滚动条的颜色 */
  border-radius: 5px; /* 滚动条的圆角 */
}

.list-group::-webkit-scrollbar-track {
  background-color: #f5f5f5; /* 滚动条轨道的颜色 */
  border-radius: 5px; /* 滚动条轨道的圆角 */
}

/* 设置滚动条默认在底部 */
.list-group {
  scroll-margin-bottom: 10px;
}



 p {
    
    background-color: burlywood;
  border: 2px solid #38da6e;
  border-radius: 10px;
  padding: 10px;
  margin-bottom: 10px;

}

</style>
